package com.atguigu.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.bean.CartAddUuBean;
import com.atguigu.utils.DateFormatUtil;
import com.atguigu.utils.KafkaUtil;
import com.atguigu.utils.MyClickHouseUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.AllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

/*
10.6 交易域加购各窗口汇总表（练习）（要开启db的DwdTradeCartAdd）
10.6.1 主要任务
	从 Kafka 读取用户加购明细数据，统计各窗口加购独立用户数，写入 ClickHouse。

 */
//todo 2.读取kafka dwd加购明细主题数据创建流
//todo 3.转为json对象
//todo 4.提取时间戳生成watermark
//todo 5.按照uid分组
//todo 6.标记加购独立用户并转化为javabean（利用richflatmap）
//todo 7.开窗聚合
//todo 8.写出数据到clickhouse
//todo 9.启动任务
public class Dws06TradeCartAddUuWindow {
    public static void main(String[] args) throws Exception {
        //todo 1.获取执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        //todo 生产环境一定要写，测试注释掉，否则每次测试都得开hdfs
//        需要从checkpoint或savepoint启动程序
//        //2.1 开启checkpoint，每隔5s钟做一次ck，并指定ck的一致性语义
//        env.enableCheckpointing(3000L, CheckpointingMode.EXACTLY_ONCE);//exactly once：默认barrier对齐
//        //2.2 设置超时时间为1min
//        env.getCheckpointConfig().setCheckpointTimeout(60*1000L);//设置超时时间设置checkpoint的超时时间为1min，是指做一次checkpoint的时间；如果超时则认为本次checkpoint失败，这个checkpoint就丢了，继续一下一次checkpoint即可
//        //2.3设置两次重启的最小时间间隔为3s
//        env.getCheckpointConfig().setMinPauseBetweenCheckpoints(3000L);
//        //2.4设置任务关闭的时候保留最后一次ck数据
//        env.getCheckpointConfig().enableExternalizedCheckpoints(
//                CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION
//        );
//        //2.5 指定从ck自动重启策略
//        env.setRestartStrategy(RestartStrategies.failureRateRestart(
//                3, Time.days(1L),Time.minutes(1L)
//        ));
//        //2.6 设置状态后端
//        env.setStateBackend(new HashMapStateBackend());//本地状态位置
//        env.getCheckpointConfig().setCheckpointStorage(
//                "hdfs://hadoop102:8020/flinkCDC/220828"
//        );//checkpoint状态位置
//        //2.7 设置访问HDFS的用户名
//        System.setProperty("HADOOP_USER_NAME","atguigu");

        //todo 2.读取kafka dwd加购明细主题数据创建流
        DataStreamSource<String> kafkaDS = env.addSource(KafkaUtil.getFlinkKafkaConsumer("dwd_trade_cart_add", "tradecartadduu_220828"));

        //todo 3.转为json对象
        SingleOutputStreamOperator<JSONObject> jsonObjDS = kafkaDS.map(new MapFunction<String, JSONObject>() {
            @Override
            public JSONObject map(String value) throws Exception {
                return JSON.parseObject(value);
            }
        });

        //todo 4.提取时间戳生成watermark
        SingleOutputStreamOperator<JSONObject> jsonObjWithWMDS = jsonObjDS.assignTimestampsAndWatermarks(
                WatermarkStrategy
                        .<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(2))
                        .withTimestampAssigner(new SerializableTimestampAssigner<JSONObject>() {
                            @Override
                            public long extractTimestamp(JSONObject element, long recordTimestamp) {
//                                return DateFormatUtil.toTs(element.getString("create_time"), true);
                                return element.getLong("create_time");
                            }
                        })
        );
        //todo 5.按照uid分组
        KeyedStream<JSONObject, String> keyByUidDS = jsonObjWithWMDS.keyBy(line -> line.getString("user_id"));


        //todo 6.标记加购独立用户并转化为javabean（利用richflatmap）
        SingleOutputStreamOperator<CartAddUuBean> javaBeanDS = keyByUidDS.flatMap(new RichFlatMapFunction<JSONObject, CartAddUuBean>() {

            private ValueState<String> lastCartAddDtState;

            @Override
            public void open(Configuration parameters) throws Exception {
                ValueStateDescriptor<String> valueStateDescriptor = new ValueStateDescriptor<>("cartADD-state", String.class);
                StateTtlConfig ttlConfig = StateTtlConfig.newBuilder(Time.days(1))
                        .setUpdateType(StateTtlConfig.UpdateType.OnCreateAndWrite)
                        .build();
                valueStateDescriptor.enableTimeToLive(ttlConfig);

                lastCartAddDtState = getRuntimeContext().getState(valueStateDescriptor);
            }

            @Override
            public void flatMap(JSONObject value, Collector<CartAddUuBean> out) throws Exception {
                //todo 获取状态
                String lastCartAddDt = lastCartAddDtState.value();

                //todo 标记加购独立用户并转化为javabean
                //获取当前时间
                String create_time = value.getString("create_time");
                Long createTs = DateFormatUtil.toTs(create_time, true);
                String curDt = DateFormatUtil.toDate(createTs);

                //定义变量
                long cartAddUVCt=0L;
                if(lastCartAddDt == null || curDt.compareTo(lastCartAddDt)>0){
                    //说明该mid今天是第一次加购
                    cartAddUVCt=1L;
                    lastCartAddDtState.update(curDt);

                    out.collect(new CartAddUuBean(
                            "",
                            "",
                            cartAddUVCt,
                            null
                    ));
                }
            }
        });

        //todo 7.开窗聚合
        SingleOutputStreamOperator<CartAddUuBean> resultDS = javaBeanDS.windowAll(TumblingEventTimeWindows.of(org.apache.flink.streaming.api.windowing.time.Time.seconds(10)))
                .reduce(new ReduceFunction<CartAddUuBean>() {
                    @Override
                    public CartAddUuBean reduce(CartAddUuBean value1, CartAddUuBean value2) throws Exception {
                        value1.setCartAddUuCt(value1.getCartAddUuCt() + value2.getCartAddUuCt());
                        return value1;//滑动滚动窗口需要return new javabean，否则一个元素所属的多个窗口会指向同一个地址

                    }
                }, new AllWindowFunction<CartAddUuBean, CartAddUuBean, TimeWindow>() {
                    @Override
                    public void apply(TimeWindow window, Iterable<CartAddUuBean> values, Collector<CartAddUuBean> out) throws Exception {
                        for (CartAddUuBean value : values) {
                            value.setStt(DateFormatUtil.toYmdHms(window.getStart()));
                            value.setEdt(DateFormatUtil.toYmdHms(window.getEnd()));
                            value.setTs(System.currentTimeMillis());
                            out.collect(value);
                        }
                    }
                });

        resultDS.print("即将写到clickhouse的数据");

        //todo 8.写出数据到clickhouse
        resultDS.addSink(MyClickHouseUtil.getSinkFunction("insert into dws_trade_cart_add_uu_window values(?,?,?,?)"));


        //todo 9.启动任务
        env.execute();

    }
}
